package 网络编程;

import java.io.IOException;
import java.net.*;
import java.util.Scanner;

/**
 * 客户端
 */
public class UdpEchoServer {
    private DatagramSocket socket=null;
    private String serverip;
    private int serverport;

    public UdpEchoServer( String serverip, int serverport) throws SocketException {
        this.socket = new DatagramSocket();
        this.serverip = serverip;
        this.serverport = serverport;
    }
    //1.先读一个数据，用scanner输入，判断是不是exit
    //2.把字符串构造成udp请求,packet，既要包含数据又要指定发给谁，要把ipSting类型转成InetAddress，并发送
    //3.从服务器获取响应，用packet获取缓冲区
   public void start() throws IOException {
       while (true) {
           Scanner scanner=new Scanner(System.in);
           String str=scanner.next();
           if(str.equals("exit")){
               return;
           }
           DatagramPacket receive=new DatagramPacket(str.getBytes(),str.getBytes().length,
                                                    InetAddress.getByName(serverip),
                                                        serverport);
           socket.send(receive);
           DatagramPacket response=new DatagramPacket(new byte[4096],4096);
           socket.receive(response);
           String res=new String(response.getData(),0,response.getLength());

           String str2=String.format("receive:%s,response:%s,ip:%s，port:%d",str
                                                                            ,res
                                                                            ,receive.getAddress()
                                                                            ,receive.getPort());//服务端的端口和ip
           System.out.println(str2);
       }
   }

    public static void main(String[] args) throws IOException {
        UdpEchoServer server=new UdpEchoServer("127.0.0.1",9090);
        server.start();
    }

}
